<template>
  <div class="uploadOuter">
    <el-card>
      <div class="uploadVideoTitle">
        <div class="UploadVideo-tab">发布视频</div>
      </div>
      <!--视频上传-->
      <div class="SingleUpload">
        <div class="SingleUpload-videoReload">
          <div class="video-title">文件上传</div>
          <p class="upload-tip">推荐采用MP4、FLV格式，可有效缩短审核转码耗时</p>
          <div class="videoUpload">
            <el-upload
              class="upload-demo"
              :show-file-list="true"
              drag
              :accept="uploadType"
              :before-upload="beforeUpload"
              :action="baseUrl+'/upload'"
              :on-progress="uploadVideoProcess"
              :on-success="uploadSuccess"
              :limit="1"
              :on-exceed="uploadExceed"
              ref="videoUpload"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
            <div>
              <el-progress class="uploadProgress" v-if="uploadProgress.progressFlag"
                           :percentage="uploadProgress.percentage"
                           :color="uploadProgress.customColors"
                           :text-inside="true"
                           :stroke-width="24"></el-progress>
            </div>

          </div>
        </div>
      </div>
      <!--图片上传-->
      <div class="EditVideo">
        <div class="EditVideo-item">
          <div class="video-title">视频封面设置</div>
          <div class="flex-content">
            <div class="cover-content">
              <el-upload
                :class="{disUploadSty:isButtonHide}"
                :on-change="imgChange"
                :on-remove="handleImgRemove"
                :on-success="imgSuccess"
                :action="baseUrl+'/upload'"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                ref="imgUpload"
                :auto-upload="false"
                accept=".jpeg,.png,.jpg"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </div>
            <div class="cover-tip">
              <div>封面长宽比16:9；</div>
              <div>格式jpeg、png；</div>
              <div>建议尺寸≥1146*644，最低尺寸≥720*405；</div>
              <div>文件大小<5MB；</div>
              <div>没有上传封面，将自动截取视频画面</div>
            </div>
          </div>
        </div>
      </div>
      <div class="EditVideo-videoTitle">
        <el-form ref="uploadForm" :model="uploadForm" :rules="uploadFormRules" label-width="80px" label-position="top">
          <el-form-item label="标题:" prop="title">
            <el-input v-model="uploadForm.title" maxlength="80" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="分类" prop="type">
            <el-cascader :props="typeProps" clearable filterable v-model="uploadForm.type"></el-cascader>
          </el-form-item>
        </el-form>
      </div>
      <div class="EditVideo-videoSubmit">
        <div class="videoSubmit-btn" @click="videoUploadHandler">立即投稿</div>
      </div>
    </el-card>
  </div>
</template>

<script>
import videoApi from "@/api/video";
import {mapGetters} from "vuex";

export default {
  name: "Upload",
  data() {
    return {
      uploadParam: {
        //文件类型列表
        videoType: ['.mp4', '.MP4', '.mov', '.avi', '.rm', '.rmvb', '.m4v', '.mkv', '.3gp', '.wmv', '.ts', '.m2ts'],
      },
      //进度条相关数据
      uploadProgress: {
        progressFlag: false,
        percentage: 0,
        customColors: [
          {color: '#f56c6c', percentage: 20},
          {color: '#e6a23c', percentage: 40},
          {color: '#5cb87a', percentage: 60},
          {color: '#1989fa', percentage: 80},
          {color: '#6f7ad3', percentage: 100}
        ]
      },
      //后端目录
      baseUrl: "http://localhost:8963",
      //图片放大dialog显隐
      dialogVisible: false,
      dialogImageUrl: '',
      //图片上传后按钮隐藏
      isButtonHide: false,
      // 上传表单
      uploadForm: {
        coverPath: undefined
      },
      // 表单验证
      uploadFormRules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请选择分类', trigger: 'blur'}
        ]
      },
      // 级联选择器配置项
      typeProps: {
        lazy: true,
        async lazyLoad(node, resolve, id = 0) {
          id = node.value || 0;
          let result = await videoApi.getVideoType(id);
          let nodes = await Promise.all(result.data.typeList.map(async (item) => {
                let response = await videoApi.judgeIsLeaf(item.id)
                return {
                  value: item.id,
                  label: item.label,
                  leaf: response.data.isLeaf
                };
              }
            )
          );
          resolve(nodes);
        }
      }
    };
  },
  computed: {
    uploadType() {
      return this.uploadParam.videoType.join(',');
    },
    ...mapGetters(["userId"])
  },
  methods: {
    // 上传文件进度条
    uploadVideoProcess(event, file, fileList) {
      this.uploadProgress.progressFlag = true;
      this.uploadProgress.percentage = parseInt(event.percent);
      if (this.uploadProgress.percentage >= 100) {
        this.uploadProgress.percentage = 100;
        setTimeout(() => {
          this.uploadProgress.progressFlag = false;
        }, 500);
      }
    },
    // 上传前的类型旁段
    beforeUpload(file) {
      let suffix = file.name.substring(file.name.lastIndexOf("."));
      if (this.uploadParam.videoType.includes(suffix)) {
        return true;
      } else {
        this.$modal.alertWarning("请上传视频相关的文件");
        return false;
      }
    },
    // 文件上传成功回调
    uploadSuccess(res, file, fileList) {
      this.uploadForm.videoPath = res.data.filePath;
      this.$modal.msgSuccess("视频添加完成");
    },
    //文件超出个数回调
    uploadExceed(files, fileList) {
      this.$modal.alertWarning("文件只允许上传一个，请先清除已上传文件");
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片状态修改
    imgChange(file, fileList) {
      this.isButtonHide = fileList.length >= 1;
    },
    //图片移除事件
    handleImgRemove(file, fileList) {
      setTimeout(() => this.isButtonHide = fileList.length >= 1,
        1000
      );
    },
    //图片上传成功
    async imgSuccess(res) {
      this.$set(this.uploadForm, "coverPath", res.data.filePath);
      let uploadForm = this.uploadForm;
      uploadForm.type = uploadForm.type[uploadForm.type.length - 1];
      uploadForm.userId = this.userId;
      await videoApi.createVideo(uploadForm);
      this.$modal.msgSuccess("视频添加成功");
      this.$router.push("/");
    },
    //视频上传处理
    videoUploadHandler: function () {
      this.$refs.uploadForm.validate(async valid => {
        if (!valid) return;
        let videoUpload = this.$refs.videoUpload;
        let imgUpload = this.$refs.imgUpload;
        if (videoUpload.uploadFiles?.length > 0) {
          if (imgUpload.uploadFiles?.length > 0) {
            imgUpload.submit();
          } else {
            let uploadForm = this.uploadForm;
            uploadForm.type = uploadForm.type[uploadForm.type.length - 1];
            uploadForm.userId = this.userId;
            await videoApi.createVideo(uploadForm);
            this.$modal.msgSuccess("视频添加成功");
            this.$router.push("/");
          }
        } else {
          return this.$modal.alertWarning("请先上传视频");
        }
      });
    }
  },
};
</script>

<style lang="less" scoped>
.uploadOuter {
  padding: 20px 100px;
  // 上传视频标题
  .uploadVideoTitle {
    width: 100%;
    height: 30px;
    border-bottom: 1px solid #e7e7e7;
    // 标题单元
    .UploadVideo-tab {
      font-size: 16px;
      height: 30px;
      color: #ff5d23;
      display: inline-block;
      vertical-align: bottom;
      position: relative;
      font-weight: 700;

      &::after {
        content: "";
        width: 64px;
        height: 3px;
        background-color: #ff5d23;
        position: absolute;
        bottom: -2px;
        left: 0;
        -webkit-border-radius: 1.5px;
        -moz-border-radius: 1.5px;
        border-radius: 1.5px;
      }
    }
  }

  //上传视频样式
  .SingleUpload {
    margin-bottom: 30px;
    padding-top: 40px;

    .video-title {
      font-size: 16px;
      color: #3c3c3c;
      margin-bottom: 15px;
      font-weight: 700;
    }

    .upload-tip {
      font-size: 12px;
      color: #999;
      margin-bottom: 15px;
    }

    .videoUpload {

    }
  }

  //上传图片样式
  .EditVideo-item {
    margin-top: 30px;
    //标题
    .video-title {
      font-size: 16px;
      color: #3c3c3c;
      margin-bottom: 20px;
      position: relative;
    }

    .flex-content {
      display: flex;

      .cover-content {
        width: 148px;
        height: 148px;

        .disUploadSty /deep/ .el-upload--picture-card {
          display: none; /* 上传按钮隐藏 */
        }
      }

      // 提示
      .cover-tip {
        color: #666;
        font-size: 12px;
        margin-left: 30px;
      }
    }
  }

  //上传表单
  .EditVideo-videoTitle {
    margin-top: 40px;
  }

  .EditVideo-videoSubmit {
    margin-top: 60px;
    margin-bottom: 40px;

    .videoSubmit-btn {
      width: 140px;
      height: 48px;
      background-color: #ff5d23;
      border-radius: 24px;
      color: #fff;
      font-size: 18px;
      text-align: center;
      line-height: 48px;
      cursor: pointer;
      display: inline-block;
      margin-right: 20px;

      &:hover {
        background-color: #f44d12;
      }
    }
  }
}
</style>
